package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOPBACKEND.entity.FAB.FABImg;
import com.burgeon.backend.SHOPBACKEND.entity.FAB.FABRelevance;
import com.burgeon.backend.SHOPBACKEND.entity.FAB.FabEntity;
import com.burgeon.backend.SHOPBACKEND.mappers.FabMapper;
import com.burgeon.backend.SHOPBACKEND.rest.QueryFABGoodsByCode;
import com.burgeon.backend.SHOPBACKEND.service.FABservice;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Service
public class FABserviceimpl implements FABservice {

    @Autowired
    private FabMapper fabMapper;
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public FABRelevance getRelevance(String code, String account) {
        Info info = GetInfo(account);
        QueryFABGoodsByCode queryFABGoodsByCode = new QueryFABGoodsByCode(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return queryFABGoodsByCode.getData(code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public FabEntity findDataByCode(String code, String account) {
        FabEntity data = fabMapper.findDataByCode(code, account);
        if (null != data) {
            data.setImg(fabMapper.getImgData(data.getId()));
        }

        return data;
    }

    @Override
    public HashMap listData(String account, int state) {

        List<FabEntity> list = fabMapper.getData(account, state);
        for (FabEntity fabEntity : list) {
            fabEntity.setImg(fabMapper.getImgData(fabEntity.getId()));
            fabEntity.setFabRelevances(fabMapper.findRelevanceByMid(fabEntity.getId()));
        }
        HashMap data = new HashMap();
        data.put("list", list);
        data.put("count", fabMapper.getDataCount(account));

        return data;
    }

    @Override
    @Transactional
    public void createData(FabEntity fabEntity, List<FABRelevance> fabRelevances, MultipartFile[] files) throws ErrorDataException {
        if (null != fabMapper.findDataByCode(fabEntity.getCode(), fabEntity.getAccount())) {
            throw new ErrorDataException("款号已存在");
        }

        try {
            fabMapper.createData(fabEntity);

            if (null!=fabRelevances&&0 != fabRelevances.size()) {
                for (FABRelevance fabRelevance : fabRelevances) {
                    fabRelevance.setMasterId(fabEntity.getId());
                    //新增
                    fabMapper.createRelevance(fabRelevance);
                }
            }


            for (MultipartFile file : files) {
                FABImg fabImg = new FABImg();
                fabImg.setFabId(fabEntity.getId());
                fabMapper.createImg(fabImg);
                addImg(file, fabEntity.getAccount(), fabImg.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public void upData(FabEntity fabEntity, List<FABRelevance> fabRelevances, MultipartFile[] files, String[] delId) throws ErrorDataException {

        try {
            fabMapper.upData(fabEntity);
            // fabMapper.delImg(fabEntity.getId());
            for (String id : delId) {
                fabMapper.delImgById(id);
            }
            fabMapper.delRelevanceByMastId(fabEntity.getId());
            if (null!=fabRelevances&&0 != fabRelevances.size()) {
                for (FABRelevance fabRelevance : fabRelevances) {
                    fabRelevance.setMasterId(fabEntity.getId());
                    //新增
                    fabMapper.createRelevance(fabRelevance);
                }
            }


            if (files.length != 0) {
                for (MultipartFile file : files) {
                    FABImg fabImg = new FABImg();
                    fabImg.setFabId(fabEntity.getId());
                    fabMapper.createImg(fabImg);
                    System.err.println(file.getName());
                    System.err.println(fabEntity.getAccount());
                    System.err.println(fabImg.getId());
                    addImg(file, fabEntity.getAccount(), fabImg.getId());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public void delData(String[] id) throws ErrorDataException {

        try {
            for (String fid : id) {
                fabMapper.delData(fid);
                fabMapper.delData(fid);
            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }

    }

    @Override
    public void delImg(String id) throws ErrorDataException {
        try {
            fabMapper.delImgById(id);
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }
    }

    void addImg(MultipartFile file, String account, String id) throws ErrorDataException {


        String fileName = file.getOriginalFilename(); //文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
        //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
        String filePath = "//root//code//img//" + account + "-fab//"; // 上传后的路径
        fileName = id + suffixName; // 新文件名

        String imgUrl = "http://lfwdcdn.cloudsmicro.com/img/" + account + "-fab//" + fileName;
        fabMapper.upImgData(id, imgUrl);
        saveFile(file, fileName, filePath);

    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath)
            throws ErrorDataException {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ErrorDataException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new ErrorDataException("系统错误");
        }
    }

    private Info GetInfo(String token) {
        return accountMapper.GetAccData(token);
    }
}
